package com.usian.springbootmysql.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.springbootmysql.dao.StuDao;
import com.usian.springbootmysql.pojo.ResultVo;
import com.usian.springbootmysql.pojo.SearchDto;
import com.usian.springbootmysql.pojo.Stu;
import com.usian.springbootmysql.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
public class StuServiceImpl extends ServiceImpl<StuDao, Stu> implements StuService {

    @Autowired
    private StuDao stuDao;

    @Override
    public ResultVo saveStu(@RequestBody Stu stu) {
//        判断 根据名称查询获取这个名字出现的次数，大于0则添加失败，返回等于0添加成功
//        QueryWrapper<Stu>queryWrapper=new QueryWrapper<Stu>();
//        queryWrapper.eq("name",stu.getName());
        LambdaQueryWrapper<Stu>lambdaQueryWrapper=new LambdaQueryWrapper<Stu>();
        lambdaQueryWrapper.eq(Stu::getName,stu.getName());
        int count = stuDao.selectCount(lambdaQueryWrapper);//相当于equals
            if (count>0){
            return new ResultVo(201,"名称存在，添加失败",null);
            }else {
                stuDao.insert(stu);
                return new ResultVo(200,"名称不存在，允许添加",null);
            }
    }

    @Override
    public List<Stu> search(int status) {
        LambdaQueryWrapper<Stu>queryWrapper=new LambdaQueryWrapper<Stu>();
        queryWrapper.eq(Stu::getStatus,status);
        List<Stu> stuList = stuDao.selectList(queryWrapper);
        return stuList;
    }

    @Override
    public List<Stu> searchVo(@RequestBody Stu stu) {
        LambdaQueryWrapper<Stu>queryWrapper=new LambdaQueryWrapper<Stu>();
        if (!StringUtils.isEmpty(stu.getName())){
            queryWrapper.like(Stu::getName,stu.getName());
        }
        if (stu.getStatus()!=null){
            queryWrapper.eq(Stu::getStatus,stu.getStatus());
        }

        List<Stu> stuList = stuDao.selectList(queryWrapper);
        return stuList;
    }

    @Override
    public IPage<Stu> findPage(SearchDto searchDto) {
        IPage<Stu>page=new Page<>(searchDto.getPage(),searchDto.getSize());
        LambdaQueryWrapper<Stu>queryWrapper=new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(searchDto.getName())){
            queryWrapper.like(Stu::getName,searchDto.getName());
        }
        if (searchDto.getStatus()!=null){
            queryWrapper.eq(Stu::getStatus,searchDto.getStatus());
        }
        IPage<Stu> stuIPage = stuDao.selectPage(page, queryWrapper);
        return stuIPage;
    }
}
